//
//  UIViewControllerAdditions.m
//  Tint
//
//  Created by Kevin Wu on 2/22/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "UIViewControllerAdditions.h"
#import "UIColorAdditions.h"


@implementation UIViewController (Tint)


#pragma mark - Debug

- (void)addButtonWithTitle:(NSString *)title selector:(SEL)selector
{
    [self addButtonWithTitle:title selector:selector type:0];
}

- (void)addButtonWithTitle:(NSString *)title selector:(SEL)selector type:(NSUInteger)type
{
#ifdef DEBUG
    NSInteger containerTag = 9070;
    
    NSMutableArray *containers = [NSMutableArray array];
    // Find all containers
    for ( int i=0; i<[self.view.subviews count]; ++i ) {
        UIView *tmp = [self.view.subviews objectAtIndex:i];
        if ( tmp.tag >= containerTag ) {
            [containers addObject:tmp];
        }
    }
    
    // Find container
    UIView *container = nil;
    for ( UIView *tmp in containers ) {
        if ( tmp.tag == (containerTag + type) ) {
            container = tmp;
            break;
        }
    }
    
    if ( container == nil ) {
        container = [[[UIView alloc] init] autorelease];
        [containers addObject:container];
        [self.view addSubview:container];
        container.tag = containerTag+type;
        container.backgroundColor = [UIColor randomColor];
    }
    
    
    // Calculate button frame
    CGFloat spacing = 4.0;
    CGFloat buttonWidth = (self.view.frame.size.width - 3 * spacing) / 2.0;
    CGFloat buttonHeight = 40.0;
    
    NSUInteger row = [container.subviews count] / 2;
    NSUInteger column = [container.subviews count] % 2;
    
    CGRect buttonFrame = CGRectMake(spacing + column * (buttonWidth + spacing), 
                                    spacing + row * (buttonHeight + spacing), 
                                    buttonWidth, 
                                    buttonHeight);
    
    // Add new button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [container addSubview:button];
    button.frame = buttonFrame;
    
    // Calculate container frame
    container.frame = CGRectMake(container.frame.origin.x, 
                                 container.frame.origin.y, 
                                 self.view.frame.size.width, 
                                 button.frame.origin.y + button.frame.size.height + spacing);
    
    // Reposition all containers
    
    CGFloat y = 0.0;
    for ( int i=0; i<[containers count]; ++i ) {
        UIView *tmp = [containers objectAtIndex:i];
        tmp.frame = CGRectMake(0.0, y, tmp.frame.size.width, tmp.frame.size.height);
        y += tmp.frame.size.height;
    }
#endif
}

@end
